<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use App\Models\User;
use App\Models\LoginLog;
use Illuminate\Support\Facades\Hash;
use App\Http\Requests\MemberRequest;
class MembersController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth']);
    }

    public function index(Request $request)
    {
        $user = Auth::user();
        $this->authorize('add', $user);

        $members = user::with('roles')->where(function ($query) use ($user) {
            if ($user->hasRole('Daili')) {
                $query->where('parent_id', '=', $user->id);
            }
        })->filter($request->all())->orderBy('created_at', 'desc')->paginate(20);

        return view('members.index', compact('members', 'user'));
    }
    public function login_logs(User $member, Request $request)
    {
        $this->authorize('destroy', $member);
        $user = Auth::user();
        $logs = LoginLog::with('user')->filter($request->all())->orderBy('created_at', 'desc')->paginate(20);
        return view('members.login_logs', compact('user', 'logs'));
    }

    public function create(User $member)
    {
        $user = Auth::user();
        $this->authorize('add', $user);
        return view('members.create_and_edit', compact('user', 'member'));
    }
    public function store(Request $request)
    {
        $user = $request->user();
        $this->authorize('add', $user);
        $data = $request->validate([
            'name' => ['required', 'string', 'not_regex:/^\\d+$/','max:32', 'unique:users'],
            'qq' => ['sometimes', 'nullable', 'numeric'],
            'password' => ['required', 'string', 'min:6', 'confirmed'],
            'kouliang' => 'sometimes|required',
            'price' => ['sometimes', 'required', 'numeric'],
            'kouliang_min' => ['sometimes', 'required', 'numeric'],
            'parent_id' => ['sometimes', 'required', 'numeric']
        ]);
        if (!$user->hasRole('Founder')) {
            $data['kouliang'] = -1;
            $data['kouliang_min'] = -1;
            $data['price'] = 0.00;
        }
        $user = $this->add($data);
        if($request->type === 'daili') {
            // 如果修改了角色 判断一下权限
            $this->authorize('destroy', $user);
            $user->assignRole('Daili');
            $user->parent_id = 0;
            $user->save();
        }
        return redirect()->route('members.index')->with('success', '成功添加一个用户！');
    }
    public function edit(User $member)
    {
        $user = Auth::user();
        $this->authorize('update', $member);
        return view('members.create_and_edit', compact('user', 'member'));
    }
    public function update(User $member, MemberRequest $request)
    {
        $this->authorize('update', $member);
        $rules = [
            'name' => ['sometimes', 'required', 'string', 'not_regex:/^\\d+$/', 'max:32', 'unique:users,name,' . $member->id],
            'email' => 'sometimes|required|string|email|max:255|unique:users,email,' . $member->id,
            'password' => 'sometimes|nullable|string|min:6|confirmed',
            'kouliang' => 'sometimes|required',
            'role' => 'sometimes|required|numeric',
            'price' => 'sometimes|required|numeric',
            'parent_id' => 'sometimes|required|numeric',
            'kouliang_min' => 'sometimes|required|numeric',
        ];
        $data = $request->validate($rules);

        // 密码为空则不修改
        if (empty($data['password'])) $data['password'] = $member->password;
        else if(!empty($data['password'])) $data['password'] = Hash::make($data['password']);

        // 只有管理员可以修改 单价 扣量比例 上级ID
        if ( ! $request->user()->hasRole('Founder')) {
            $data['kouliang'] = $member->kouliang;
            $data['price'] = $member->price;
            $data['role'] = $member->role;
            $data['parent_id'] = $member->parent_id;
            $data['kouliang_min'] = $member->kouliang_min;
        }

        // 用户角色修改 (必须有管理员权限)
        if(!$member->hasRole('Founder') && $request->user()->hasRole('Founder')) {
            if($request->type === 'daili') {
                $member->assignRole('Daili');
                // 当用户被提升为代理时， 移除上级
                $data['parent_id'] = 0;
            }
            else $member->removeRole('daili');
            // 判断一下上级ID 填写是否正确
            if ($data['parent_id'] > 0 ) {
                $parent_user = User::find($data['parent_id']);
                if (!$parent_user || !$parent_user->hasRole('Daili')) return redirect()->route('members.edit', $member->id)->withErrors('上级ID必须是一个代理！');
            }
        }

        $member->update($data);

        if(isset($data['role'])) return redirect()->route('members.index')->with('success', '操作成功');
        return redirect()->route('members.edit', $member->id)->with('success', '修改成功！');
    }
    public function ban(User $member, Request $request)
    {
        $this->authorize('destroy', $member);
        $member->role = $request->input('role', 0);
        $member->save();
        return redirect()->route('members.index')->with('success', '操作成功');
    }
    public function destroy(User $member)
    {
        // 只有管理员才可以删除用户
        $this->authorize('destroy', $member);
        $member->delete();
        return redirect()->route('members.index')->with('success', '删除成功！');
    }
    protected function add(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'qq' => $data['qq'],
            'password' => Hash::make($data['password']),
            'price' => $data['price'],
            'kouliang' => $data['kouliang'],
            'kouliang_min' => $data['kouliang_min'],
            'parent_id' => $data['parent_id']
        ]);
    }
}
